package com.bayair.doctor.utils;

import android.util.Log;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
  多次快速点击判断
 */
public class MultiQuickClick {

    //保存click时间
    private static List<Long> list = new ArrayList<>();
    //多次点击间隔
    private static final int MIN_CLICK_INTERVAL_TIME = 3000;
    //时间隔内允许点击次数
    private static final int MIN_CLICK_COUNT = 3;

    public static boolean isMultiClick() {
        long curTime = System.currentTimeMillis();
        Log.d("aaaa", "点击时间: " + curTime);
        Log.d("aaaa", "list: " + list);
        if (list.isEmpty()) {
            list.add(curTime);
        } else {
            if (isValid(curTime)) {
                list.add(curTime);
                if (list.size() >= MIN_CLICK_COUNT + 1) {
                    if (list.size() > MIN_CLICK_COUNT + 1) {
                        //清除list中最小的个值
                        removeMin();
                    }
                    return true;
                }
            } else {
                List<Long> removeList = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    Long l = list.get(i);
                    if (curTime - l > MIN_CLICK_INTERVAL_TIME) {
                        removeList.add(l);
                    }
                }
                list.removeAll(removeList);
                list.add(curTime);
            }
        }
        return false;
    }

    /**
     移除list最小的值（距当前最远的时间）
     */
    private static void removeMin() {
        Long min = Collections.min(list);
        list.remove(min);
    }

    //此次点击是否在限制时间内
    private static boolean isValid(long cur) {
        for (Long time : list) {
            if (cur - time > MIN_CLICK_INTERVAL_TIME) {
                return false;
            }
        }
        return true;
    }
}
